import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/circle/controllers/circle_detail_controller.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CircleDetailView extends GetView<CircleDetailController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          controller.title ?? '',
        ),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          FocusScope.of(Get.context!).requestFocus(FocusNode());
        },
        child: Container(
          color: Colors.white,
          child: Stack(
            children: [
              SafeArea(
                bottom: true,
                child: Obx(() {
                  final height = controller.height.value;
                  return Container(
                    margin: EdgeInsets.only(bottom: 50),
                    child: SmartRefresher(
                      controller: controller.controller,
                      onLoading: () => controller.loadData(),
                      child: Obx(() {
                        final count = controller.comments.value.length;

                        return ListView.builder(
                          itemCount: 1 + (count > 0 ? count + 2 : 0),
                          itemBuilder: (ctx, index) {
                            if (index == 0) {
                              return _contentView();
                            } else if (index == 1) {
                              return height > 1
                                  ? Container(height: 8, color: MColor.xFFF2F2F2)
                                  : Container();
                            } else if (index == 2) {
                              return height > 1 ? _commentTitleView : Container();
                            } else {
                              return height > 1 ? _commentView(index - 3) : Container();
                            }
                          },
                        );
                      }),
                    ),
                  );
                }),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: _bottomView,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _contentView() {
    final model = controller.detailEntity.value;
    if (model.content == null) {
      return Container();
    }

    InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          useShouldOverrideUrlLoading: true,
          mediaPlaybackRequiresUserGesture: false,
        ),
        android: AndroidInAppWebViewOptions(
          useHybridComposition: true,
          useWideViewPort: true,
          initialScale: 1,
        ),
        ios: IOSInAppWebViewOptions(
          allowsInlineMediaPlayback: true,
        ));
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      height: controller.height.value.toDouble(),
      color: Colors.white,
      child: InAppWebView(
        initialOptions: options,
        onWebViewCreated: (ctx) {
          controller.webViewController = ctx;
          var content = model.content ?? '';
          final head = '<html>'
              '<head>'
              '<meta charset="utf-8">'
              '<meta name="viewport" id="viewport" content=\'width=device-width,'
              'height=device-height,target-desitydpi=high-dpi,initial-scale=1,minimum-scale=1,'
              'maximum-scale=1,user-scalable=no\'>'
              '<title>About us</title>'
              '</head>'
              '<style type=\'text/css\'>'
              '*{margin: 0;padding: 0;outline: none;cursor: pointer;}.main{width: 100%;margin:0 auto;}img{width: 100%;display: block;margin: 0;padding: 0;border: 0;}p:empty{line-height:0;}p{margin:10px 0;}'
              '</style>';
          content = head + content;
          content = content + '</html>';
          ctx.loadData(data: content);
        },
        onProgressChanged: (ctx, progress) async {
          if (progress == 100) {
            Future.delayed(Duration(milliseconds: 300), () async {
              int contentHeight = await ctx.getContentHeight() ?? 0;
              controller.height.value = contentHeight;
            });
          }
        },
        onLoadStop: (ctx, url){
          EasyLoading.dismiss();
        },
      ),
    );
  }

  get _commentTitleView {
    return Container(
      padding: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 16),
      child: Text(
        'Comments',
        style: MFont.semi_Bold15.apply(color: MColor.xFF333333),
      ),
    );
  }

  Widget _commentView(int index) {
    return Container(
      padding: EdgeInsets.only(left: 12, right: 12, bottom: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Image.asset(Assets.imagesAvator, width: 40, height: 40),
              SizedBox(width: 8),
              Text(
                controller.comments.value[index].nickname ?? '',
                style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
              ),
              SizedBox(width: 8),
              Text(
                controller.comments.value[index].commentDate ?? '',
                style: MFont.regular10.apply(color: MColor.xFF999999),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(left: 48),
            child: Text(
              controller.comments.value[index].content ?? '',
              style: MFont.regular13.apply(color: MColor.xFF666666),
              strutStyle: StrutStyle(height: 1.5),
            ),
          )
        ],
      ),
    );
  }

  get _bottomView {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: MColor.xFFF2F2F2)),
      ),
      child: Row(
        children: [
          Container(
            width: 240,
            child: TextField(
              controller: controller.editingController,
              keyboardType: TextInputType.multiline,
              decoration: InputDecoration(
                isDense: true,
                labelStyle: MFont.regular15.apply(color: MColor.xFF333333),
                filled: true,
                fillColor: MColor.xFFF2F2F2,
                prefixIcon: Image.asset(
                  Assets.imagesDeviceEdit,
                ),
                hintText: LocaleKeys.circle_add_comment.tr,
                prefixIconConstraints: BoxConstraints(maxHeight: 18, minWidth: 40),
                contentPadding: EdgeInsets.only(top: 6, bottom: 6, right: 12),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.transparent, width: 0),
                  borderRadius: BorderRadius.circular(17),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.transparent, width: 0),
                  borderRadius: BorderRadius.circular(17),
                ),
                constraints: BoxConstraints(minWidth: 34),
              ),
              onSubmitted: (text) {
                FocusScope.of(Get.context!).requestFocus(FocusNode());
              },
              maxLines: 3,
              minLines: 1,
            ),
          ),
          Spacer(),
          TextButton(
            onPressed: () {
              controller.fetchSendText();
            },
            child: Text(
              'Send',
              style: MFont.semi_Bold15.apply(color: MColor.xFF333333),
            ),
          ),
          IconButton(
            padding: EdgeInsets.zero,
            constraints: BoxConstraints(maxHeight: 34),
            onPressed: () {
              controller.fetchAgree();
            },
            icon: Image.asset(
              Assets.imagesCircleAgree,
              width: 24,
              height: 24,
            ),
          ),
        ],
      ),
    );
  }
}
